package cc.spider.core.queue;

import cc.spider.model.TaskInfo;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 实现优先级阻塞队列
 * taskInfo的priority越大优先级越高
 */
public class PriorityQueue implements ITaskQueue {
    PriorityBlockingQueue<TaskInfo> queue = new PriorityBlockingQueue<>(100, new Comparator<TaskInfo>() {
        @Override
        public int compare(TaskInfo oriTask, TaskInfo tagTask) {
            return oriTask.getPriority() - tagTask.getPriority();
        }
    });

    @Override
    public boolean enqueue(TaskInfo task) {
        return queue.offer(task);
    }

    @Override
    public TaskInfo dequeue() {
        try {
            return queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }
}
